import React, { useEffect, useState, useRef } from 'react'
import ReactDOM from 'react-dom'
import { Modal } from 'antd'
import Draggable from 'react-draggable';

const { success, info, warning, error, confirm } = Modal;

const ModalComponent = (props) => {

    const { children, closeModal, onOk, onCancel, title, ...otherProps } = props;
    const okListenerRef = useRef(null)
    const cancelListenerRef = useRef(null);
    const draggleRef = useRef(null);
    const [disabled, setDisabled] = useState(false)
    const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 })
    const setOkListener = (cb) => {
        okListenerRef.current = cb
    }
    const setCancelLister = (cb) => {
        cancelListenerRef.current = cb
    }
    const handleOk = async () => {
        let res = "ok", okListener = okListenerRef.current
        if (okListener) {
            res = await okListener()
            if (res === false) {
                return
            }
        }
        onOk(res)
    }

    const handleCancel = async () => {
        let res = "cancel", cancelListener = cancelListenerRef.current
        if (cancelListener) {
            res = await cancelListener()
            if (res === false) {
                return
            }
        }
        onCancel(res)
    }

    let childrenClone;
    if (children.type.name) {
        childrenClone = React.cloneElement(children, {
            setOkListener,
            setCancelLister,
            closeModal
        })
    } else {
        childrenClone = children
    }
    const handleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current.getBoundingClientRect();
        setBounds({
            bounds: {
                left: -targetRect.left + uiData.x,
                right: clientWidth - (targetRect.right - uiData.x),
                top: -targetRect.top + uiData.y,
                bottom: clientHeight - (targetRect.bottom - uiData.y),
            },
        })
    };
    return (
        <Modal
            {...otherProps}
            visible={true}
            children={childrenClone}
            onOk={handleOk}
            onCancel={handleCancel}
            modalRender={modal => (
                <Draggable
                    disabled={disabled}
                    bounds={bounds}
                    onStart={(event, uiData) => handleStart(event, uiData)}
                >
                    <div ref={draggleRef}>{modal}</div>
                </Draggable>
            )}
            title={
                <div
                    style={{
                        width: '100%',
                        cursor: 'move',
                    }}
                    onMouseOver={() => {
                        if (disabled) {
                            setDisabled(false)
                        }
                    }}
                    onMouseOut={() => {
                        setDisabled(true)
                    }}
                    onFocus={() => { }}
                    onBlur={() => { }}
                >
                    {title}
                </div>
            }
        />
    )
}

const Instance = () => {
    return {
        show(props = {}) {
            const div = document.createElement('div')
            return new Promise((resolve, reject) => {
                const handleOk = (res) => {
                    ReactDOM.unmountComponentAtNode(div)
                    try {
                        document.body.removeChild(div)
                    } catch (err) {

                    }
                    resolve(res)
                }
                const handleCancel = (res) => {
                    ReactDOM.unmountComponentAtNode(div)
                    try {
                        document.body.removeChild(div)
                    } catch (err) {

                    }
                    resolve(res)
                }
                const closeModal = (res = "close") => {
                    //手动销毁modal
                    ReactDOM.unmountComponentAtNode(div)
                    try {
                        document.body.removeChild(div)
                    } catch (err) {

                    }
                    resolve(res)
                    //return res
                }
                if (props.bindClose) {
                    //通过绑定来关闭弹框，在children为dom时使用
                    props.bindClose(closeModal)
                    //props.footer = null
                }
                document.body.appendChild(div);
                ReactDOM.render(
                    <ModalComponent
                        {...props}
                        closeModal={closeModal}
                        onOk={handleOk}
                        onCancel={handleCancel}
                    />
                    , div)
            })
        },
        info,
        success,
        error,
        warning,
        confirm
    }
}

let m = Instance();

export default m

//仅提供一种modal思路